<script lang="ts" setup>
import { getPatientConsultOrderListAPI } from '@/apis/common'
import { deletePatientOrderByIdAPI, putPatientOrderCancelByIdAPI } from '@/apis/order'
import {
  OrderStatus,
  type ConsultOrderItem,
  type GetPatientConsultOrderListParams,
} from '@/types/consult'
import { ref } from 'vue'

// 接收父组件传递的参数
const props = defineProps<{
  type: number
}>()

// 定义查询参数
const query = ref<Required<GetPatientConsultOrderListParams>>({
  type: props.type, // 问诊类型
  current: 1, // 页码
  pageSize: 10, // 页大小
})

// 获取订单列表
const list = ref<ConsultOrderItem[]>([])
// 总条数
const total = ref(0)
// 总页数
const pageTotal = ref(0)

// 加载状态
const loadMoreStatus = ref<UniHelper.UniLoadMoreStatus>('loading')

// 获取订单列表
const getList = async (isMore = false) => {
  // 加载状态 - 加载中
  loadMoreStatus.value = 'loading'
  // 发送请求
  const res = await getPatientConsultOrderListAPI(query.value)
  // 判断是否是加载更多
  if (isMore) {
    list.value.push(...res.data.rows) // 订单列表数据
  } else {
    list.value = res.data.rows // 订单列表数据
  }

  total.value = res.data.total // 总条数
  pageTotal.value = res.data.pageTotal // 总页数
  // 判断是否还有更多数据
  if (query.value.current < pageTotal.value) {
    // 加载状态 - 请求完成
    loadMoreStatus.value = 'more'
  } else {
    // 加载状态 - 请求完成
    loadMoreStatus.value = 'noMore'
  }
}

// 上拉加载更多
const getMoreData = async () => {
  // 判断是否还有更多数据
  if (query.value.current >= pageTotal.value) return
  // 页码 + 1
  query.value.current++
  // 获取订单列表
  await getList(true)
}
// 获取订单列表
getList()

//下拉刷新状态
const refresherTriggered = ref(false)
//下拉刷新事件
const onRefresh = async () => {
  // 下拉刷新状态
  refresherTriggered.value = true
  // 页码重置
  query.value.current = 1
  // 重新加载数据
  await getList()
  // 下拉刷新状态
  refresherTriggered.value = false
}

// 是否显示查看更多
const activeShowMoreId = ref('')

// 取消订单
const handleCancelOrder = (item: ConsultOrderItem) => {
  uni.showModal({
    title: '提示',
    content: '确定取消订单吗？',
    confirmColor: '#16c2a3',
    success: async (res) => {
      if (res.confirm) {
        await putPatientOrderCancelByIdAPI(item.id)
        // 提示
        uni.showToast({
          title: '取消订单成功',
          icon: 'success',
        })
        // 更新订单状态
        item.status = OrderStatus.YiQuXiao
        item.statusValue = '已取消'
      }
    },
  })
}

// 删除订单
const handleDeleteOrder = (item: ConsultOrderItem) => {
  uni.showModal({
    title: '提示',
    content: '确定删除订单吗？',
    confirmColor: '#16c2a3',
    success: async (res) => {
      if (res.confirm) {
        // 后端：调用删除订单接口
        await deletePatientOrderByIdAPI(item.id)
        // 提示
        uni.showToast({
          title: '删除订单成功',
          icon: 'success',
        })
        // 前端：删除订单项（注意：这里循环项 item 命名可能冲突）
        list.value = list.value.filter((v) => v.id !== item.id)
      }
    },
  })
}

// 继续咨询
const handleContinueConsult = (item: ConsultOrderItem) => {
  uni.navigateTo({
    url: `/subpkg_consult/pages/room/room?orderId=${item.id}`,
  })
}
</script>

<template>
  <scroll-view
    refresher-enabled
    refresher-background="#f6f6f6"
    class="uni-scroll-view"
    scroll-y
    @click="activeShowMoreId = ''"
    @scrolltolower="getMoreData"
    @refresherrefresh="onRefresh"
    :refresher-triggered="refresherTriggered"
  >
    <view class="consult-list">
      <view class="consult-list-item" v-for="item in list" :key="item.id">
        <view class="consult-header">
          <view class="label">
            <image class="doctor-avatar" src="/static/uploads/doctor-avatar.jpg" />
            <text>{{ item.typeValue }}（自动分配医生）</text>
          </view>
          <!-- 多个条件判断可以用 includes 化简  -->
          <text
            class="status"
            :class="{
              'color-1': item.status === OrderStatus.DaiZhiFu,
              'color-2': [OrderStatus.DaiJieZhen, OrderStatus.ZiXunZhong].includes(item.status),
              'color-3': [OrderStatus.YiWanCheng, OrderStatus.YiQuXiao].includes(item.status),
            }"
          >
            {{ item.statusValue }}
          </text>
        </view>
        <navigator
          class="consult-body"
          hover-class="none"
          :url="`/subpkg_consult/pages/order_detail/order_detail?id=${item.id}`"
        >
          <uni-list :border="false">
            <uni-list-item :border="false" title="病情描述" :right-text="item.illnessDesc" />
            <uni-list-item :border="false" title="价格" :right-text="`¥ ${item.payment}`" />
            <uni-list-item :border="false" title="创建时间" :right-text="item.createTime" />
          </uni-list>
        </navigator>
        <view class="consult-footer">
          <view class="uni-button more" v-if="item.status === OrderStatus.YiWanCheng">
            <text
              class="label"
              @click="activeShowMoreId = activeShowMoreId === item.id ? '' : item.id"
              >更多</text
            >
            <uni-transition :show="activeShowMoreId === item.id">
              <view class="list">
                <view class="list-item">查看处方</view>
                <view class="list-item" @click="handleDeleteOrder(item)">删除订单</view>
              </view>
            </uni-transition>
          </view>
          <template v-if="item.status === OrderStatus.DaiZhiFu">
            <button class="uni-button minor" @click="handleCancelOrder(item)">取消订单</button>
            <button class="uni-button">去支付</button>
          </template>

          <template v-if="item.status === OrderStatus.DaiJieZhen">
            <button class="uni-button minor" @click="handleCancelOrder(item)">取消订单</button>
            <button class="uni-button" @click="handleContinueConsult(item)">继续咨询</button>
          </template>

          <template v-if="item.status === OrderStatus.ZiXunZhong">
            <button class="uni-button" @click="handleContinueConsult(item)">继续咨询</button>
          </template>

          <template v-if="item.status === OrderStatus.YiWanCheng">
            <button class="uni-button minor" @click="handleContinueConsult(item)">问诊记录</button>
            <button v-if="item.evaluateId" class="uni-button minor">查看评价</button>
            <button v-else class="uni-button">去评价</button>
          </template>

          <template v-if="item.status === OrderStatus.YiQuXiao">
            <button class="uni-button minor" @click="handleDeleteOrder(item)">删除订单</button>
            <button class="uni-button">咨询其它医生</button>
          </template>
        </view>
      </view>

      <!-- 加载状态 -->
      <uni-load-more
        :status="loadMoreStatus"
        color="#C3C3C5"
        :icon-size="16"
        :content-text="{
          contentdown: '上拉显示更多',
          contentrefresh: '数据正在加载中',
          contentnomore: '没有更多数据了',
        }"
      />
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import './styles.scss';
</style>
